package com.cby.library.common.network

import com.cby.library.common.BuildConfig
import com.cby.library.tool.network.stetho.NetworkInterceptor
import com.cby.library.tool.network.stetho.NetworkListener
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import java.lang.Exception
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

object HttpClientProvider {
    private const val CONNECTION_TIME_OUT = 7
    private const val READ_TIME_OUT = 7

    val defaultHttpClient: OkHttpClient
        get() = getHttpClient()

    /**
     * 获取http client
     */
    fun getHttpClient(vararg interceptors: Interceptor): OkHttpClient {
        val builder = OkHttpClient.Builder()
        if (BuildConfig.DEBUG) {
            //debug模式下打印http请求日志
            val logging = LogInterceptor()
            builder.addInterceptor(logging)
            //添加监听
            builder.eventListenerFactory(NetworkListener.get())
            //添加网络拦截器，用于捕获请求信息
            builder.addNetworkInterceptor(NetworkInterceptor())
        }

        //遍历拦截器
        for (interceptor in interceptors) {
            builder.addInterceptor(interceptor)
        }

        builder.connectTimeout(CONNECTION_TIME_OUT.toLong(), TimeUnit.SECONDS)
            .writeTimeout(READ_TIME_OUT.toLong(), TimeUnit.SECONDS)
            .readTimeout(READ_TIME_OUT.toLong(), TimeUnit.SECONDS)

        //设置https的证书支持
        createSSLSocketFactory()?.let { builder.sslSocketFactory(it, MyTrustManager()) }
        builder.hostnameVerifier { _, _ -> true }
        builder.retryOnConnectionFailure(true)

        return builder.build()
    }

    private fun createSSLSocketFactory(): SSLSocketFactory? {
        var ssfFactory: SSLSocketFactory? = null
        try {
            val sc = SSLContext.getInstance("SSL")
            sc.init(null, arrayOf<TrustManager>(MyTrustManager()), SecureRandom())
            ssfFactory = sc.socketFactory
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ssfFactory
    }

    internal class MyTrustManager : X509TrustManager {
        override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {}
        override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {}
        override fun getAcceptedIssuers(): Array<X509Certificate?> {
            return arrayOfNulls(0)
        }
    }
}